﻿using System;
using System.Collections.Generic;
using System.Drawing;

namespace TodoSoft.Controls
{
	public class TreeGridRow
	{
		public static int DefaultHeight = 16;

		public readonly List<TreeGridRow> Children = new List<TreeGridRow>();

		public int Top { get; set; }
		public int Bottom
		{
			get { return Top+Height; }
			set { Height = value-Top; }
		}

		public int Height { get; set; }
		public bool Expanded = true;
		public bool ShowChildsVisibleSwitcher = true;
		public TreeGridRow ParrentRow;
		public TreeGridGroup Group;
		public object Tag;
		public event EventHandler ChildrenVisibleChanged;
		public object[] Cells;

		public TreeGridRow (TreeGridGroup group, params object[] fields)
		{
			Group = group;
			Cells = fields;
			Height = DefaultHeight;
		}
		
		public void Paint(Graphics graphics)
		{
			int width = 0;
			for (int columnIndex = 0; columnIndex < Group.Columns.Count; columnIndex++ )
			{
				var column = Group.Columns[columnIndex];
                PaintCell(graphics, Cells[columnIndex], column);
				width += column.Width;
			}

			graphics.DrawLine( Group.BorderPen, 0, Bottom - 1, width, Bottom - 1);
		}

		public void PaintCell(Graphics graphics, object data, TreeGridColumn column)
		{
			var padding = column.Padding ?? new Margins();

			var text = column.Format(data);
			var cellRect = new Rectangle(
				column.Left + padding.Left, 
				Top + padding.Top,
				column.Width - padding.Left - padding.Right,
				Height - padding.Top - padding.Bottom);

			var font = Group.Font;

			if (column.ShrinkToFit)
			{
				var size = graphics.MeasureString(text, font);
				while (size.Height > cellRect.Height || size.Width > cellRect.Width && font.Size > column.MinFontSize)
				{
					var newFont = new Font(font.Name, font.Size - 0.5f, font.Style);
					if(font != Group.Font)
						font.Dispose();
					font = newFont;
					size = graphics.MeasureString(text, font);
				} 
			}

			graphics.DrawString(
					text,
					font,
					Group.TextBrush,
					cellRect,
					column.StringFormat);

			if (font != Group.Font)
				font.Dispose();
		}

		internal void SetChildsVisible(bool childsVisible)
		{
			foreach (var row in Children)
			{
				row.Expanded = childsVisible;
			}

			if (ChildrenVisibleChanged != null)
				ChildrenVisibleChanged(this, EventArgs.Empty);
		}

		public Dictionary<string, object> Data;
	}
}
